package com.edu.employee.controller.test;

import com.edu.commons.ServiceCode;
import com.edu.commons.ServiceException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ProjectName: summer-project
 * @Titile: UserLoginInterceptor
 * @Author: Lucky
 * @Description: 开发拦截器
 */
@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    // alt + insert

    /**
     * 前置拦截：拦截之前要处理的逻辑
     * @param request
     * @param response
     * @param handler
     * @return 返回true，放行，如果返回false，就代表拦截了，不能往下执行。
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasText(token)){
            throw new ServiceException(ServiceCode.ERROR,"token不能为空");
        }
        //todo 校验token ...
        return true;

    }

    /**
     * 处理拦截
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 拦截已经完成：回调方法
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
